<?php
$caption = BUtils::T('restaurants_lbl');
$special_lbl = BUtils::T('special_lbl');
$see_detail_lbl = BUtils::T('see_detail_lbl');

$this->pageTitle = BUtils::T('meta_title_seo_restaurant') . ' | Yamii';
if (empty($_GET['tag'])) {
	$this->breadcrumbs=array(
		$caption,
	);
} else {
	$searchTag = isset($GLOBALS['LNG'][$_GET['tag']]) ? $GLOBALS['LNG'][$_GET['tag']] : $_GET['tag'];
	$this->breadcrumbs=array(
		$caption => Yii::app()->createUrl('/'.$this->id),
		$searchTag,
	);
	$this->pageTitle = $caption . '/' . $searchTag;
}

$tags_lbl = BUtils::T('tags_lbl');

//make map data
$default = array();
foreach ($rows as $k => $r) {
	if (!empty($r['latitude'])) {
		$default['lat'] = $r['latitude'];
		$default['lng'] = $r['longitude'];
		break;
	}
}
if (empty($default)) {
	$default['lat'] = 60.15;
	$default['lng'] = 25.03;
}

//make pager buttons
if ($page > 1) {
	$btn_prev = '<a class="btn btn-small load-prev" data-offset="'.($offset-20).'" data-page="'.($page-1).'" href="?page='.($page-1).'"><i class="icon-chevron-left"></i></a>';
} else {
	$btn_prev = '<a class="btn btn-small load-prev" disabled="disabled" data-offset="'.($offset-20).'" data-page="'.($page-1).'" href="?page='.($page-1).'"><i class="icon-chevron-left"></i></a>';
}
$btn_next = '<a class="btn btn-small load-next" data-offset="'.($offset+20).'" data-page="'.($page+1).'" href="?page='.($page+1).'"><i class="icon-chevron-right"></i></a>';
?>
<div class="row">
	<div class="span8" style="position:relative;">
		<div class="box_white">
			<div class="media scroll-map">
				<div id="theMapPopup" class="map-popup-fields"></div>
				<div id="theMap" style="height:100%;" data-latitude="<?php echo $default['lat']; ?>" data-longitude="<?php echo $default['lng']; ?>" data-zoom="14"></div>
			</div>
		</div>
		<div style="margin-bottom:8px; position:absolute; top:10px; left:10px;">
			<a class="btn btn-small locate-me"><i class="gicon-riflescope"></i> <?php echo BUtils::T('locate_me_btn'); ?></a>
			<span class="label label-inverse none" id="my-location"></span>
		</div>
	</div>
	<div class="span4">
		<div class="venueResults box_white fill-left clearfix">
			<div id="error_result" class="panel" style="display:none;">
				<h3>Search Error</h3>
				<p>Whoops, something went wrong. Please try again, or if the problem persists, please <?php echo CHtml::link('email us', Yii::app()->createUrl('/yamii/feedback'), array('class'=>'popup-window')) ?> to report the error.</p>
			</div>
			<div id="success_result" class="scroll-list">
<?php
$markers = array();
$total = count($rows);
foreach ($rows as $k => $r) {
	if (!empty($r['distance'])) {
		if ($r['distance'] < 1) $r['distance'] = sprintf('%d mi', $r['distance'] * 1000);
		else $r['distance'] = sprintf('%.1f km', $r['distance']);
		
		$r['distance'] = '<i class="gicon-direction"></i> ' . $r['distance'];
	}
	
	$bizLink = Yii::app()->createUrl($this->id.'/view', array('id'=>$r['id']));
	$bizLogoLink = BUtils::GetBusinessPictureUrl($r['url_logo']);
	
	$bizTagLinks = $this->getTagLinks($r['cuisine_style'], ' ', 1);
	if (!empty($bizTagLinks)) $bizTagLinks .= ' ' . $this->getTagLinks($r['cuisine_type'], ' ', 1);
	if (!empty($bizTagLinks)) $bizTagLinks = '<i class="gicon-cutlery"></i> ' . $bizTagLinks;
	
	$bizSpecials = null;
	if (!empty($r['specials']) and $r['specials'] > 0) {
		$specialListLink = Yii::app()->createUrl('/special/view', array('id'=>$r['id_special']));
		$tips = ($r['specials'] > 1) ? $r['specials'] . ' ' . $special_lbl : $r['specials'] . ' ' . $special_lbl;
		$bizSpecials = '<span class="specialsTab tooltip-onright" title="'.$tips.'"><a class="link popup-window" href="'.$specialListLink.'">'.$r['specials'].'</a></span>';
	}
	
	$pinId = 'mid_' . $r['id'];
	$pinIndex = $total - $k - 1;
	echo <<<HTML
<div class="venueItem clearfix map-locate" id="{$pinId}" data-pin-id="{$pinId}" data-pin-i="{$pinIndex}">
	<div class="bizLogo">
		<a href="{$bizLink}"><img src="{$bizLogoLink}" width="60" alt="{$r['name']}" class="img-polaroid" /></a>
	</div>
	<div class="bizInfo">
		<h4 class="bizTitle"><span class="bizName">{$r['name']}</span></h4>
		<div class="bizOffer">{$bizSpecials}</div>
	</div>
	<div class="clearfix"></div>
	<div class="bizFooter">
		<div class="tags left">{$bizTagLinks}</div>
		<div class="distance right">{$r['distance']}</div>
		<div class="clearfix"></div>
	</div>
</div>
HTML;
	
	//create markers
	$bizSpecialsMarker = null;
	if (!empty($r['specials']) and $r['specials'] > 0) {
		$specialListLink = Yii::app()->createUrl('/special/view', array('id'=>$r['id_special']));
		$bizSpecialsMarker = '<span class="specialsTab"><a class="link" href="'.$specialListLink.'" onclick="popup_window(this);">'.$r['specials'].'</a></span>';
	}
	$marker = array(
		'id' => $r['id'],
		'lat' => $r['latitude'],
		'lng' => $r['longitude'],
		'specials' => (int)$r['specials'],
	);
	$marker['body'] = <<<HTML
<div class="place-sider clearfix relative">
	{$bizSpecialsMarker}
	<div class="bizInfo">
		<div class="name">{$r['name']}</div>
		<div class="address">
			<i class="gicon-google-maps gicon-white"></i> <span class="street">{$r['address']}</span><br />
			<i class="gicon-blank"></i> <span class="city">{$r['postcode']} {$r['city']}</span>
		</div>
HTML;
	if (!empty($r['phone'])) {
		$marker['body'] .= '<div class="phone"><i class="gicon-phone gicon-white"></i> '.$r['phone'].'</div>';
	}
	$marker['body'] .= '<div class="see-detail"><a href="'.$bizLink.'">'.$see_detail_lbl.'</a></div>';
	$marker['body'] .= '</div></div>';
	$markers[] = $marker;
}
?>
			</div>
		</div>
		<div class="clearfix fill-left">
			<div class="">
				<?php echo $btn_prev; ?><?php echo $btn_next; ?>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
<?php
//let the merchant with specials in the last
echo 'var markers =' . json_encode(array_reverse($markers)) . ';';
?>
var mapCav = null;
var activePin = {id:null,style:2};
var locate = {};
$(function() {
	//bind map search button
	$('.load-next').click(function () {request_list($(this)); return false;});
	$('.load-prev').click(function () {request_list($(this)); return false;});
	
	//bind markers
	mapCav = $("#theMap").isMapCanvas('<?php echo Yii::app()->baseUrl; ?>', 1);
	$.map(markers, function(v, i) {
		if (v.lat && v.lng) {
			var pinId = 'mid_' + v.id;
			mapCav.pin(pinId, {
				style:(v.specials > 0) ? 4 : 2,
				latitude: v.lat,
				longitude: v.lng,
				onClick: function() {
					mapInfoWindow(pinId, v);
				}
			});
		}
	});
	//bind map locate
	$('.map-locate').click(function() {
		var pinId = $(this).data('pin-id');
		var pinIndex = $(this).data('pin-i');
		if (pinIndex >= 0) {
			mapInfoWindow(pinId, markers[pinIndex]);
		}
	});
	
	var $window = $(window);
	var height = $window.height() - 210;
	if (height < 600) height = 600;
	$('.scroll-map').attr('style', 'height:' + height + 'px;');
	$('.scroll-list').attr('style', 'height:' + height + 'px;');
	$window.bind("scroll resize", function() {
		var height = $window.height() - 210;
		if (height < 600) height = 600;
		$('.scroll-map').attr('style', 'height:' + height + 'px;');
		$('.scroll-list').attr('style', 'height:' + height + 'px;');
	});
	
	//locate me
	initialize();
	$('.locate-me').click(function () {
		findMe();
	});
});


function request_list(_pager) {
	var offset = 0;
	if (_pager != null) {
		if (_pager.attr('disabled')) return false;
		offset = _pager.data('offset');
	}
	
	var _request = $.ajax({
		url: location.href,
		type: 'GET',
		data: {offset:offset, lat:locate.lat, lng:locate.lng},
		dataType: 'json',
		beforeSend: function(xhr) {
			if (_pager != null) _pager.attr('disabled', true);
		},
		error: function() {
			if (_pager != null) _pager.attr('disabled', false);
		}
	});
	_request.done(function(msg) {
		if (msg.html == '') {
			location.reload();
			return;
		}
		
		if (_pager != null) {
			_pager.attr('disabled', false);
			if (_pager.hasClass('load-prev')) {
				var _offset = _pager.data('offset');
				if (_offset > 19) {
					_pager.data('offset', _offset - 20);
					$('.load-next').data('offset', _offset + 20);
				} else {
					_pager.attr('disabled', true);
					_pager.data('offset', 0);
					$('.load-next').data('offset', 20);
				}
				$('.load-next').show().attr('disabled', false);
			} else {
				var _offset = _pager.data('offset');
				if (_offset < 500) {
					if (msg.number < 20) _pager.attr('disabled', true);
					_pager.data('offset', _offset + 20);
					$('.load-prev').data('offset', _offset - 20);
				} else {
					_pager.attr('disabled', true);
					_pager.data('offset', 0);
					$('.load-prev').data('offset', 480);
				}
				$('.load-prev').show().attr('disabled', false);
			}
		}
		
		$('#success_result').html('');
		$('#success_result').append(msg.html);
		
		//bind markers
		mapCav.removeAllPins();
		mapCav.removeAllBubbles();
		$.map(msg.markers, function(v, i) {
			if (v.lat && v.lng) {
				var pinId = 'mid_' + v.id;
				mapCav.pin('mid_' + v.id, {
					style: (v.specials > 0) ? 4 : 2,
					latitude: v.lat,
					longitude: v.lng,
					onClick: function() {
						mapInfoWindow(pinId, v);
					}
				});
			}
		});
		if (msg.markers) mapCav.setCenter(msg.markers[0].lat, msg.markers[0].lng);
		//bind popup-windows
		$('.popup-window').colorbox({transition:'none'});
		//set tooltips
		$('.tooltip-onleft').tooltip({placement:'left'});
		$('.tooltip-onright').tooltip({placement:'right'});
		$('.tooltip-onbottom').tooltip({placement:'bottom'});
		$('.tooltip-ontop').tooltip({placement:'top'});
		
		//bind map locate
		$('.map-locate').click(function() {
			var pinId = $(this).data('pin-id');
			var pinIndex = $(this).data('pin-i');
			if (pinIndex >= 0) {
				mapInfoWindow(pinId, msg.markers[pinIndex]);
			}
		});
		
		$('#error_result').hide();
	});
	_request.fail(function(jqXHR, textStatus) {
		$('#error_result').show();
		$('#success_result').hide();
	});
}

function mapInfoWindow(pinId, marker) {
	if (!marker.lat || !marker.lng) {return;}
	//mapCav.panTo(marker.lat, marker.lng)
	//clear last activePinId
	if (activePin.id) {
		$('#'+activePin.id).removeClass('active');
		mapCav.pin(activePin.id, {style:activePin.style, zIndex:0});
	}
	mapCav.removeAllBubbles();
	mapCav.bubble(pinId, {
		latitude: marker.lat,
		longitude: marker.lng,
		content: marker.body,
		offsetVertical: -4,
		size: 'small'
	});
	activePin.id = pinId;
	activePin.style = (marker.specials>0) ? 4:2;
	mapCav.pin(pinId, {style: 3, zIndex: 9999});
	//scroll tp that pin
	$('#success_result').scrollTo('#'+pinId, 500, {queue:true});
	$('#'+pinId).addClass('active');
}

function findMe() {
	mapCav.findMe(function(lat, lng){
		locate.lat = lat;
        locate.lng = lng;
		var geocoder = new google.maps.Geocoder();
		var latlng = new google.maps.LatLng(locate.lat, locate.lng);
		geocoder.geocode({'latLng': latlng}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
				$('#my-location').fadeIn('fast').html(results[0]['formatted_address']);
				//request_list();
			} else {
				$('#my-location').fadeOut('fast');
			};
        });
	});
}
function initialize() {
    var geocoder = new google.maps.Geocoder();
    if (google.loader.ClientLocation) {
        locate.lat = google.loader.ClientLocation.latitude;
        locate.lng = google.loader.ClientLocation.longitude;
		mapCav.panTo(locate.lat, locate.lng);
        var latlng = new google.maps.LatLng(locate.lat, locate.lng);
        geocoder.geocode({'latLng': latlng}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
				$('#my-location').fadeIn('fast').html(results[0]['formatted_address']);
				//request_list();
			} else {
				$('#my-location').fadeIn('fast');
			};
        });
    }
}
</script>